'use strict';

const Service = require('egg').Service;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

class BannerService extends Service {
    // 广告列表
    async page(query) {
      const { ctx } = this;
      let config = {
        where:{
          isDel:0
        },
        order:[
          ['createTime', 'DESC']
        ],
        attributes: { 
          exclude: ['isDel','delTime','banners'],          
        }
      };
      if(query.name){
        config.where.name = {
          [Op.like]:`%${query.name}%`
        }
      }
      if(!query.pageNO){
        query.pageNO = 1;
      }
      if(!query.pageSize){
        query.pageSize = 10;
      }
      config.offset = (query.pageNO-1)*query.pageSize;
      config.limit = query.pageSize;
      return await ctx.model.Banner.findAndCountAll(config);
    }

    // 广告详情
    async detail(query) {
      const { ctx } = this;
      let config = {
        where:{
          isDel:0,
          id:query.id
        },
        attributes: { 
          exclude: ['isDel','delTime'] 
        }
      };
      return await ctx.model.Banner.findOne(config);
    }

    // 广告添加
    async add(data) {
      const { ctx } = this;
      return await ctx.model.Banner.create({
        name:data.name,
        identity:data.identity,
        desc:data.desc?data.desc:'',
        banners:data.banners?JSON.stringify(data.banners):'',
        status:data.status,
        createTime:new Date().getTime(),
        updateTime:new Date().getTime(),
        delTime:0
      });
    }

    // 广告编辑
    async edit(data) {
      const { ctx } = this;
      return await ctx.model.Banner.update({
        name:data.name,
        identity:data.identity,
        desc:data.desc?data.desc:'',
        banners:data.banners?JSON.stringify(data.banners):'',
        status:data.status,
        updateTime:new Date().getTime()
      },{
        where:{
          id:data.id
        }
      });
    }

    // 广告删除
    async del(data) {
      const { ctx } = this;
      return await ctx.model.Banner.update({
        isDel:1,
        delTime:new Date().getTime()
      },{
        where:{
          id:data.id
        }
      });
    }

    // 广告修改状态
    async status(data) {
      const { ctx } = this;
      return await ctx.model.Banner.update({
        status:data.status,
        updateTime:new Date().getTime()
      },{
        where:{
          id:data.id
        }
      });
    }

    // 根据唯一标识获取广告详情
    async getIdentitydetail(query) {
        const { ctx } = this;
        let config = {
          where:{
            isDel:0,
            identity:query.identity
          },
          attributes: ['id']
        };
        return await ctx.model.Banner.findOne(config);
    }
  }

  module.exports = BannerService;
